package com.sgcc.ln.pmos.e_ln_mall.activity;

import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.sgcc.ln.pmos.arouter.mall.MallArouterPath;
import com.sgcc.ln.pmos.common.base.BaseActivity;
import com.sgcc.ln.pmos.common.bean.BaseResponse;
import com.sgcc.ln.pmos.common.http.HttpInterConst;
import com.sgcc.ln.pmos.common.http.HttpRequestUtils;
import com.sgcc.ln.pmos.common.http.MvcNetCallback;
import com.sgcc.ln.pmos.common.http.MvpNetCallback;
import com.sgcc.ln.pmos.common.utils.BigDecimalUtils;
import com.sgcc.ln.pmos.common.utils.DateUtils;
import com.sgcc.ln.pmos.common.utils.DialogUtil;
import com.sgcc.ln.pmos.common.utils.OptionPickerUtil;
import com.sgcc.ln.pmos.common.utils.TimePickerUtil;
import com.sgcc.ln.pmos.common.utils.UserManager;
import com.sgcc.ln.pmos.common.widget.MyEditText;
import com.sgcc.ln.pmos.common.widget.TitleBar;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.ln.pmos.e_ln_mall.bean.InvitationListBean;
import com.sgcc.ln.pmos.e_ln_order.bean.PackageOrdersBean;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 发布邀约
 */
@Route(path = MallArouterPath.MALL_ISSUEDINVITATION)
public class IssuedInvitationActivity extends BaseActivity {

    private TitleBar mTitleBar;
    private MyEditText mEtUsername;
    private RelativeLayout mRlStartTime;
    private TextView mTvStartTime;
    private RelativeLayout mRlEndTime;
    private TextView mTvEndTime;
    private LinearLayout mLlNewPower, mLlMonthPower;
    private CheckBox mCheckboxPower;
    private TextView tvPower;
    private MyEditText mEtMonthPower;
    private MyEditText mEtXing;
    private LinearLayout mLlNan;
    private ImageView mIvNan;
    private LinearLayout mLlNv;
    private ImageView mIvNv;
    private MyEditText mEtPhone;
    private RelativeLayout mRlPeriodTime, mRlMonthPower;
    private TextView mTvPeriodTime;
    private TextView tv_btn;
    private RelativeLayout mRlContractElectricity;
    private TextView mTvContractElectricity;
    private RelativeLayout mRlMarketLinkage;
    private TextView mTvMarketLinkage;
    private RelativeLayout mRlHopeTerminationWay;
    private TextView mTvHopeTerminationWay;
    private RelativeLayout mRlImmediatelyRelease;
    private RelativeLayout rl_period_validity;
    private TextView tv_period_validity;
    private NestedScrollView mNsvContent;
    private Calendar startSelect;
    private Calendar end;
    private String selectTime;
    private Date startDate;

    private int surname = 0;// 0先生 1女士
    private int isDayparting = -1; //是否分时段（0不限，1是，2否）
    private int isPredeterminedEnergy = -1;//是否约定电量（0不限，1是，2否）
    private int isInterlock = -1;//价格是否与市场联动（0不限，1是，2否）
    private int terminationType = -1; //希望解约方式（0不限，1支付违约金解约，2双方协商解约）
    private String validityType; //生效时间（7天，15天，30天）


    private List<String> options1Items = new ArrayList<>();

    @Autowired
    public InvitationListBean.DataDTO.ListDTO invitationData;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_issuedinvitation;
    }

    @Override
    protected void initViews() {
        super.initViews();
        findViewByIds();
        setViewAction();
        if (null != invitationData)
            setData();
    }

    private void setData() {
        mEtUsername.setText(invitationData.getMembersUsersName());
        mTvStartTime.setText(DateUtils.getStrng_to_Times_ymd_6(invitationData.getIntentionStartDate()));
        startDate = DateUtils.getStrng_to_Times_ymd_7(invitationData.getIntentionStartDate());
        mTvEndTime.setText(DateUtils.getStrng_to_Times_ymd_6(invitationData.getIntentionEndDate()));
        tvPower.setText(BigDecimalUtils.onKeep3Decimal(invitationData.getYearEnergyAvg()));
        mCheckboxPower.setChecked(!TextUtils.isEmpty(invitationData.getUserMonthEnergy()));

        mLlMonthPower.setVisibility(!TextUtils.isEmpty(invitationData.getUserMonthEnergy()) ?
                View.VISIBLE : View.GONE);
        mRlMonthPower.setVisibility(!TextUtils.isEmpty(invitationData.getUserMonthEnergy()) ?
                View.VISIBLE : View.GONE);

        if (!TextUtils.isEmpty(invitationData.getUserMonthEnergy())) {
            mEtMonthPower.setText(BigDecimalUtils.onKeep3Decimal(invitationData.getUserMonthEnergy()));
        }

        String contactName = invitationData.getContactName();
        String surname = "";
        if (!TextUtils.isEmpty(contactName)
                && contactName.length() > 2) {
            if (contactName.endsWith("先生")) {
                this.surname = 0;
                mIvNv.setBackgroundResource(R.mipmap.issued_invitation_select);
                mIvNan.setBackgroundResource(R.mipmap.issued_invitation_selected);
            }

            if (contactName.endsWith("女士")) {
                this.surname = 1;
                mIvNan.setBackgroundResource(R.mipmap.issued_invitation_select);
                mIvNv.setBackgroundResource(R.mipmap.issued_invitation_selected);
            }


            surname = contactName.substring(0, contactName.length() - 2);
        }
        mEtXing.setText(surname);

        mEtPhone.setText(invitationData.getContactPhone());
        isDayparting = invitationData.getIsDayparting(); //是否分时段（0不限，1是，2否）
        isPredeterminedEnergy = invitationData.getIsPredeterminedEnergy();//是否约定电量（0不限，1是，2否）
        isInterlock = invitationData.getIsInterlock();//价格是否与市场联动（0不限，1是，2否）
        terminationType = invitationData.getTerminationType(); //希望解约方式（0不限，1支付违约金解约，2双方协商解约）


        mTvPeriodTime.setText(invitationData.getIsDaypartingStr());
        mTvContractElectricity.setText(invitationData.getIsPredeterminedEnergyStr());
        mTvMarketLinkage.setText(invitationData.getIsInterlockStr());
        mTvHopeTerminationWay.setText(invitationData.getTerminationTypeStr());
        tv_period_validity.setText(invitationData.getDurationDay());
    }

    private void setViewAction() {
        mNsvContent.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                KeyboardUtils.hideSoftInput(IssuedInvitationActivity.this);
            }
        });
        mLlNv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                KeyboardUtils.hideSoftInput(IssuedInvitationActivity.this);
                surname = 1;
                mIvNan.setBackgroundResource(R.mipmap.issued_invitation_select);
                mIvNv.setBackgroundResource(R.mipmap.issued_invitation_selected);
            }
        });
        mLlNan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                KeyboardUtils.hideSoftInput(IssuedInvitationActivity.this);
                surname = 0;
                mIvNan.setBackgroundResource(R.mipmap.issued_invitation_selected);
                mIvNv.setBackgroundResource(R.mipmap.issued_invitation_select);
            }
        });

        mRlStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startSelect = Calendar.getInstance();
                startSelect.add(Calendar.MONTH, 1);
//                startSelect.set(startSelect.get(Calendar.YEAR), startSelect.get(Calendar.MONTH) + 1, 1);
                KeyboardUtils.hideSoftInput(IssuedInvitationActivity.this);
                end = Calendar.getInstance();
                end.set(end.get(Calendar.YEAR) + 100, 11, 31);

                selectTime = mTvStartTime.getText().toString().trim();

                TimePickerUtil.getInstance()
                        .setRangDate(startSelect, end)
                        .setType(new boolean[]{true, true, false, false, false, false})
                        .setSelectime(selectTime)
                        .setFormat("yyyy年MM月")
                        .setOnTimeSelectListener(new OnTimeSelectListener() {
                            @Override
                            public void onTimeSelect(Date date, View view) {
                                startDate = date;
                                selectTime = getTime(date);
                                mTvStartTime.setText(selectTime);

                                int compareTo = mTvStartTime.getText().toString().trim().
                                        compareTo(mTvEndTime.getText().toString().trim());
                                if (compareTo > 0) {
                                    mTvEndTime.setText("");
                                }
                            }
                        }).build();
            }
        });
        mRlEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null == startDate) {
                    ToastUtils.showLong("请先选择开始月份");
                    return;
                }

                startSelect = Calendar.getInstance();
                if (startDate != null) {
                    startSelect.setTime(startDate);
                } else {
                    startSelect.add(Calendar.MONTH, 1);
                }
                KeyboardUtils.hideSoftInput(IssuedInvitationActivity.this);
                end = Calendar.getInstance();
                end.set(end.get(Calendar.YEAR) + 100, 11, 31);

                selectTime = mTvEndTime.getText().toString().trim();

                TimePickerUtil.getInstance()
                        .setRangDate(startSelect, end)
                        .setType(new boolean[]{true, true, false, false, false, false})
                        .setSelectime(selectTime)
                        .setFormat("yyyy年MM月")
                        .setOnTimeSelectListener(new OnTimeSelectListener() {
                            @Override
                            public void onTimeSelect(Date date, View view) {
                                selectTime = getTime(date);
                                mTvEndTime.setText(selectTime);
                            }
                        }).build();
            }
        });

        mCheckboxPower.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    mLlMonthPower.setVisibility(View.VISIBLE);
                    mRlMonthPower.setVisibility(View.VISIBLE);
                } else {
                    mLlMonthPower.setVisibility(View.GONE);
                    mRlMonthPower.setVisibility(View.GONE);
                }
            }
        });

        mRlPeriodTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                options1Items.clear();
                options1Items.add("不限");
                options1Items.add("是");
                options1Items.add("否");
                KeyboardUtils.hideSoftInput(IssuedInvitationActivity.this);
                OptionPickerUtil.getInstance().setOnOptionsSelectListener(new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        isDayparting = options1; //是否分时段（0不限，1是，2否）

                        //返回的分别是三个级别的选中位置
                        String s = options1Items.get(options1);
                        mTvPeriodTime.setText(s);
                    }
                }).build().setPicker(options1Items);
            }
        });

        mRlContractElectricity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                options1Items.clear();
                options1Items.add("不限");
                options1Items.add("是");
                options1Items.add("否");
                KeyboardUtils.hideSoftInput(IssuedInvitationActivity.this);
                OptionPickerUtil.getInstance().setOnOptionsSelectListener(new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        isPredeterminedEnergy = options1;//是否约定电量（0不限，1是，2否）
                        //返回的分别是三个级别的选中位置
                        String s = options1Items.get(options1);
                        mTvContractElectricity.setText(s);
                    }
                }).build().setPicker(options1Items);
            }
        });
        mRlMarketLinkage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                options1Items.clear();
                options1Items.add("不限");
                options1Items.add("是");
                options1Items.add("否");
                KeyboardUtils.hideSoftInput(IssuedInvitationActivity.this);
                OptionPickerUtil.getInstance().setOnOptionsSelectListener(new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        isInterlock = options1;//价格是否与市场联动（0不限，1是，2否）
                        //返回的分别是三个级别的选中位置
                        String s = options1Items.get(options1);
                        mTvMarketLinkage.setText(s);
                    }
                }).build().setPicker(options1Items);
            }
        });
        mRlHopeTerminationWay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                options1Items.clear();
                options1Items.add("不限");
                options1Items.add("支付违约金解约");
                options1Items.add("双边协商解约");
                KeyboardUtils.hideSoftInput(IssuedInvitationActivity.this);
                OptionPickerUtil.getInstance().setOnOptionsSelectListener(new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        terminationType = options1; //希望解约方式（0不限，1支付违约金解约，2双方协商解约）
                        //返回的分别是三个级别的选中位置
                        String s = options1Items.get(options1);
                        mTvHopeTerminationWay.setText(s);
                    }
                }).build().setPicker(options1Items);
            }
        });

        rl_period_validity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                options1Items.clear();
                options1Items.add("7日");
                options1Items.add("15日");
                options1Items.add("30日");
                KeyboardUtils.hideSoftInput(IssuedInvitationActivity.this);
                OptionPickerUtil.getInstance().setOnOptionsSelectListener(new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        String s = options1Items.get(options1);
                        validityType = s.substring(0, s.length() - 1);
                        tv_period_validity.setText(s);
                    }
                }).build().setPicker(options1Items);
            }
        });

        mRlImmediatelyRelease.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                post();

            }
        });
    }

    public String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月");
        return format.format(date);
    }


    private void findViewByIds() {
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mNsvContent = (NestedScrollView) findViewById(R.id.nsv_content);
        mEtUsername = (MyEditText) findViewById(R.id.et_username);
        mRlStartTime = (RelativeLayout) findViewById(R.id.rl_start_time);
        mTvStartTime = (TextView) findViewById(R.id.tv_start_time);
        mRlEndTime = (RelativeLayout) findViewById(R.id.rl_end_time);
        mTvEndTime = (TextView) findViewById(R.id.tv_end_time);
        mLlNewPower = (LinearLayout) findViewById(R.id.ll_new_power);
        mLlMonthPower = (LinearLayout) findViewById(R.id.ll_month_power);
        mCheckboxPower = (CheckBox) findViewById(R.id.checkbox_power);
        tvPower = findViewById(R.id.tv_power);
        mEtMonthPower = (MyEditText) findViewById(R.id.et_month_power);
        mEtXing = (MyEditText) findViewById(R.id.et_xing);
        mLlNan = (LinearLayout) findViewById(R.id.ll_nan);
        mIvNan = (ImageView) findViewById(R.id.iv_nan);
        mLlNv = (LinearLayout) findViewById(R.id.ll_nv);
        mIvNv = (ImageView) findViewById(R.id.iv_nv);
        mEtPhone = (MyEditText) findViewById(R.id.et_phone);
        mRlPeriodTime = (RelativeLayout) findViewById(R.id.rl_period_time);
        mRlMonthPower = (RelativeLayout) findViewById(R.id.rl_month_power);
        mTvPeriodTime = (TextView) findViewById(R.id.tv_period_time);
        tv_btn = (TextView) findViewById(R.id.tv_btn);
        mRlContractElectricity = (RelativeLayout) findViewById(R.id.rl_contract_electricity);
        mTvContractElectricity = (TextView) findViewById(R.id.tv_contract_electricity);
        mRlMarketLinkage = (RelativeLayout) findViewById(R.id.rl_market_linkage);
        mTvMarketLinkage = (TextView) findViewById(R.id.tv_market_linkage);
        mRlHopeTerminationWay = (RelativeLayout) findViewById(R.id.rl_hope_termination_way);
        mTvHopeTerminationWay = (TextView) findViewById(R.id.tv_hope_termination_way);
        mRlImmediatelyRelease = (RelativeLayout) findViewById(R.id.rl_Immediately_release);
        rl_period_validity = (RelativeLayout) findViewById(R.id.rl_period_validity);
        tv_period_validity = (TextView) findViewById(R.id.tv_period_validity);

        String energyHis = UserManager.getUserBean().getEnergyHis();
        String reslut = BigDecimalUtils.onKeep3Decimal(energyHis);
        tvPower.setText(reslut);

        mEtUsername.setText(UserManager.getUserBean().getMemberName());

        mTitleBar.setTitle(null != invitationData ? "编辑意向" : "发布意向");
        tv_btn.setText("保存");
        mTitleBar.setRightIcon(R.mipmap.go_main, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goMainActivity();
            }
        });
    }


    private void post() {

        String startTime = mTvStartTime.getText().toString().trim();
        if (TextUtils.isEmpty(startTime)) {
            ToastUtils.showLong("请选择预计购买周期开始时间");
            return;
        }
        String endTime = mTvEndTime.getText().toString().trim();
        if (TextUtils.isEmpty(endTime)) {
            ToastUtils.showLong("请选择预计购买周期结束时间");
            return;
        }
        String startTime1 = startTime.replace("年", "-").replace("月", "-") + "01";
        String endTime1 = endTime.replace("年", "-").replace("月", "-") + "01";
        String monthPower;
        if (mCheckboxPower.isChecked()) {
            monthPower = mEtMonthPower.getText().toString().trim();
            if (TextUtils.isEmpty(monthPower)) {
                ToastUtils.showLong("请输入月预计用电量");
                return;
            }
        } else {
            monthPower = "";
        }


        int compareTo = startTime.compareTo(endTime);
        if (compareTo > 0) {
            ToastUtils.showShort("预计购买周期结束时间应晚于预计购买周期开始时间");
            return;
        }

        String xing = mEtXing.getText().toString().trim();
        if (TextUtils.isEmpty(xing)) {
            ToastUtils.showLong("请输入联系人姓氏");
            return;
        }
        String phone = mEtPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showLong("请输入联系人电话");
            return;
        }
        if (!RegexUtils.isMobileExact(phone)) {
            ToastUtils.showShort("请输入正确的联系电话");
            return;
        }

        if (isDayparting == -1) {
            ToastUtils.showShort("请选择是否分时段");
            return;
        }
        if (TextUtils.isEmpty(validityType)) {
            ToastUtils.showShort("请选择生效时间");
            return;
        }
        if (isPredeterminedEnergy == -1) {
            ToastUtils.showShort("请选择是否约定电量");
            return;
        }
        if (isInterlock == -1) {
            ToastUtils.showShort("请选择价格是否与市场联动");
            return;
        }
        if (terminationType == -1) {
            ToastUtils.showShort("请选择希望解约方式");
            return;
        }

        if (mCheckboxPower.isChecked()) {
            double v1 = Double.parseDouble(monthPower);//输入的月用电量
            double v = Double.parseDouble(UserManager.getUserBean().getEnergyHis());//历史
            if (v1 < v * 0.8f || v1 > v * 1.2f) {//判断 如果输入的月用电量/ 小于历史的0.8 或者大于 历史的1.2 弹窗提示
                DialogUtil.showConfirm(mContext, "提示",
                        "您填写的月预计用电量，与历史月均用电量出入较大，请确认是否准确！", new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                post1(startTime1, endTime1, monthPower, xing, phone);
                            }
                        });
            } else {
                post1(startTime1, endTime1, monthPower, xing, phone);
            }
        } else {
            post1(startTime1, endTime1, monthPower, xing, phone);
        }

    }

    private void post1(String startTime, String endTime, String monthPower, String xing, String phone) {

        Map<String, Object> params = new HashMap<>();
        if (null != invitationData)
            params.put("guid", invitationData.getGuid());//id(新增不需要，修改需要传)
        params.put("membersUsersId", UserManager.getUserBean().getUserId());//市场主体ID（新增时取用户信息memberId）
        params.put("membersUsersName", UserManager.getUserBean().getMemberName());//用户名称（新增时取用户信息memberName）
        params.put("intentionStartDate", startTime);//预计购买周期开始
        params.put("intentionEndDate", endTime);//预计购买周期结束
        params.put("userMonthEnergy", monthPower);//月预计用电量
        params.put("yearEnergyAvg", UserManager.getUserBean().getEnergyHis());//历史月均用电量（取用户信息energyHis）
        params.put("contactName", xing + (surname == 0 ? "先生" : "女士"));//联系人姓氏（先生女士自己拼接的）
        params.put("contactPhone", phone);//联系电话
        params.put("isDayparting", isDayparting); //是否分时段（0不限，1是，2否）
        params.put("isPredeterminedEnergy", isPredeterminedEnergy); //是否约定电量（0不限，1是，2否）
        params.put("isInterlock", isInterlock); //价格是否与市场联动（0不限，1是，2否）
        params.put("terminationType", terminationType); //希望解约方式（0不限，1支付违约金解约，2双方协商解约）
        params.put("durationDay", validityType); //生效时间

        params.put("_t", System.currentTimeMillis());
        HttpRequestUtils.getInstance().request(params, HttpInterConst.SAVE_DATA_INVITATION, new MvcNetCallback<BaseResponse>(true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
            }

            @Override
            public void onResponse(BaseResponse response, int id) {
                super.onResponse(response, id);
                if (response != null) {
                    if (response.isSuccess()) {
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        if (!TextUtils.isEmpty(response.getMsg())) {
                            ToastUtils.showLong(response.getMsg());
                        }
                    }
                }

            }
        });

    }


}
